package com.lb.api;

import com.lb.base.util.RequestUtils;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.lb.base.constants.BaseConstants.MDC_KEY_TRACE_ID;


/**
 * 请求跟踪拦截器
 *
 * @author xiemingzhi
 * @since 1.0
 */
public class ApiTraceInterceptor implements HandlerInterceptor, Ordered {

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        String traceId = RequestUtils.getTraceId(request);
        MDC.put(MDC_KEY_TRACE_ID, traceId);
        return true;
    }


    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) {
        MDC.clear();
    }
}
